USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_mode_val') BEGIN
	DROP  FUNCTION  tsql.fn_mode_val
	PRINT '<<< DROP FUNCTION tsql.fn_mode_val - Completed with SUCCESS >>>'
END
GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_mode_val
Type:			User defined function 
Owner:					
Description:	Returns the most common value in a coma sepparated list of values 
Parameters:		@list = list of values comma delimited
				@item_value = value to find
Dependens on:  	fn_split
Usage:			SELECT [tsql].[fn_mode_val] ('1,2,2,2,3,4,5')
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_mode_val&referringTitle=Documentation		
Version:		20120904
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		09/04/2012 - Adrian E Dudau - Function created
================================================================================================*/

CREATE FUNCTION [tsql].[fn_mode_val] (@list NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) 
AS

BEGIN
	DECLARE	@RetVal AS NVARCHAR(MAX) = NULL;

	WITH cteMode AS 
		(
		SELECT item_value
			 , item_cnt = COUNT(item_value)	
			 , item_cnt_max = COUNT(COUNT(item_value)) OVER(PARTITION BY COUNT(item_value))
		FROM [tsql].[fn_split](@list,',') 
		GROUP BY item_value 	
		)

	SELECT TOP 1 @RetVal = CASE WHEN item_cnt_max > 1 THEN NULL ELSE item_value END 
	FROM cteMode  
	ORDER BY item_cnt DESC 

	RETURN @RetVal 
END

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_mode_val') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_mode_val - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_mode_val - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------


